﻿using System;
using System.Web;
using System.Linq;
using System.Web.Mvc;
using Framework.MVC;
using Billing.IService.Entry;
using System.Configuration;
using Recharge.Models;
using Recharge.Expand;
using Account.IService.Entry;
using Recharge.Entry;
using System.Collections.Generic;
using Identity.IService.Entry;
using Framework.Common.Entry;
using Framework.Common.Event;
using Framework.Common.Utils;
using System.Text;
using Log.Model;
using Common.IService;
using Framework.MVVM.Model;
using Log.IService;
using Common.Service;
using Log.Service;


namespace Recharge.Controllers
{
    public class RechargeController : AsyncControllerBase
    {
        #region Field
        private static readonly string m_new_error = ConfigurationManager.AppSettings["NewRechargeError"];
        private static readonly string m_new_cooike = ConfigurationManager.AppSettings["NewCooike"];

        private readonly static string m_user_resource = ConfigurationManager.AppSettings["user_resource"];
        private readonly static string m_vc_resource = ConfigurationManager.AppSettings["verifycode_resource"];

        private readonly static string m_order_done = ConfigurationManager.AppSettings["OrderDone"];
        private readonly static string m_done = ConfigurationManager.AppSettings["Done"];

        private const char m_split = ';';

        #region temp

        private readonly static string[] m_array = new string[] { "p1_MerId", "r0_Cmd", "r1_Code", "r2_TrxId", "r3_Amt", "r4_Cur", "r5_Pid", "r6_Order", "r7_Uid", "r8_MP", "r9_BType", "hmac" };

        #endregion temp

        #endregion Field

        #region New

        public void NewAsync(string type,string source) {
            HttpCookie user = Request.Cookies[m_user_resource];
            HttpCookie verifycode = Request.Cookies[m_vc_resource];
            int amount = 0;
            ReChargeAccountModel model = new ReChargeAccountModel
            {
                IdentityCode = user != null ? user.Value : null,
                Source = Request.UserHostAddress,
                AccountName = Request.Form["user"],
                RechargeOrderAmount = int.TryParse(Request.Form["amount"], out amount) ? amount : 0,
                RechargeOrderType = type,
                VerifyCode = verifycode != null ? verifycode.Value : null,
                VerifyValue = Request.Form["verifycode"],
                RechargeOrderSource = source
            };

            this.InitConfig<IDictionary<string, object>>("mvc:redirect:recharge:new", (controller, dictionary) =>
            {
                ViewBag.Redirect = dictionary;
            });
            InitModel(model);
            OnAsyncDataComplete(this, new DataEventArgs<KeyValuePair<string, object>>(new KeyValuePair<string, object>("model", model)));
        }

        public ActionResult NewCompleted(RechargeOrderEntry entry,ReChargeAccountModel model, string error) {
            //if (entry == null)
            //{
            //    this.WriteInfo("region", model.RechargeOrderSource, m_new_cooike);
            //    this.WriteInfo("amount", model.RechargeOrderAmount.ToString(), m_new_cooike);
            //    this.WriteInfo("error", error, m_new_cooike);
            //    IDictionary<string, object> dictionary = ViewBag.Redirect;
            //    string key = "failed:" + model.RechargeOrderType;
            //    return Redirect(dictionary.ContainsKey(key) ? (string)dictionary[key] : m_new_error);
            //}
            return Content(entry != null ? entry.code : error);
        }

        #endregion New

        #region Index

        public void IndexAsync(string code)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            ShowReChargeOrderModel model = new ShowReChargeOrderModel
            {
                IdentityCode = user != null ? user.Value : null,
                RechargeOrderCode = code,
                Source = Request.UserHostAddress
            };
            
            InitModel(model);
            this.InitPageConfig("master:recharge");
        }

        public ActionResult IndexCompleted(RechargeOrderEntry order, AccountEntry account, double exchange, Framework.Extention.Billing.Entry.BillingEntry billing)
        {
            if (order == null || account == null || billing == null || exchange<=0)
                return Redirect(m_new_error);


            ViewData["amount"] = order.amount;
            ViewData["code"] = order.code;
            ViewData["name"] = account.name;
            ViewData["exchange"] = exchange;
            ViewData["billing"] = billing;

            return View();
        }

        #endregion Index

        #region Done

        public void DoneAsync(string code)
        {
            RechargeDoneModel model = new RechargeDoneModel {
                Source = Request.UserHostAddress,
                Params = Request.HttpMethod == "POST" ? HttpHelper.GetParams(Request.Form) : HttpHelper.GetParams(Request.QueryString),
                Type = code
            };

            this.InitAccount("name");
            InitModel(model);
            this.InitPageConfig("master:default");
        }

        public ActionResult DoneCompleted(bool result,string code)
        {
            if (!result)
                return Redirect(m_new_error);
            ViewData["code"] = code;
            return View();
        }

        #endregion Done

        #region QueryPage

        public void QueryPageAsync(int size, int page)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            RechargeOrderQueryPageModel model = new RechargeOrderQueryPageModel
            {
                IdentityCode = user != null ? user.Value : null,
                Source = Request.UserHostAddress,
                RechargeOrderType = Request.Form["type"],
                BeginTime = Request.Form["begin"],
                EndTime = Request.Form["end"],
                PageIndex = page <=0 ? 1 : page,
                PageSize = size <= 0 || size>10 ? 10 : size
            };
            this.InitAccount("name");
            InitModel(model);
            this.InitPageConfig("master:recharge:querypage");
            this.InitConfig<IDictionary<string, KeyValueEntry<string, double>>>("data:recharge:source", (controller, dictionary) =>
            {
                ViewData["source"] = dictionary;
            });
            this.InitConfig<IDictionary<int, object>>("data:recharge:status", (controller, dictionary) =>
            {
                ViewData["status"] = dictionary;
            });
        }

        public ActionResult QueryPageCompleted(int size, int page, int count, RechargeOrderEntry[] list)
        {

            if (list != null)
            {
               ViewData["list"] = list.OrderByDescending(item => DateTime.Parse(item.indate));
            }

            ViewData["count"] = count;
            return View();
        }

        #endregion QueryPage

        #region OrderDone

        [AcceptVerbs(HttpVerbs.Post)]
        public void OrderdoneAsync(string code)
        {
            RechargeOrderDoneModel model = new RechargeOrderDoneModel
            {
                Source = Request.UserHostAddress,
                Params = HttpHelper.GetParams(Request.Form),
                Type = code,
                RechargeOrderStatus = 1,
                Header = Request.UserAgent
            };

            InitModel(model);
        }

        public ActionResult OrderdoneCompleted(bool result, RechargeOrderEntry entry)
        {
            entry = new RechargeOrderEntry { receiver = "00002012083112412128_570334313", sourceCode = "OP000001", amount = 1, code = "08310000001z" };
            string id = RechargeHelper.PostUser(Request.UserAgent, entry.receiver, entry.sourceCode);
            if (!string.IsNullOrWhiteSpace(id))
            {
                string content = string.Empty;
                bool test = RechargeHelper.PostTemp(Request.UserAgent, id, entry.amount, entry.code, "S1", out content);
            }
            return Content(result?"success":string.Empty);
        }

        #endregion OrderDone

        #region Distribute

        public ActionResult Distribute(string code)
        {
            StringBuilder paramstr = new StringBuilder();
            foreach (var key in m_array)
            {
                paramstr.AppendFormat(paramstr.Length <= 0 ? "{0}={1}" : "&{0}={1}", key, GetQueryString(key, Request.Url.Query, '&'));
            }

            string order = Request.Params["r1_Code"];
            string type = Request.Params["r9_BType"];

            string content = string.Empty;
            if (string.Equals(order, "1") && string.Equals(type, "2"))
            {
                content = RechargeHelper.Distribute(string.Format(m_order_done, code), "POST", paramstr.ToString());
            }
            else {
                content = RechargeHelper.Distribute(string.Format(m_done, code), "POST", paramstr.ToString());
            }

            return Content(content);
        }

        #endregion Distribute

        #region Private

        private static string GetQueryString(string strParaName, string strUrl, char strSplitChar)
        {
            string result = "";

            string[] strUrlArg = strUrl.Split(strSplitChar);

            for (int i = 0; i < strUrlArg.Length; i++)
            {
                if (strUrlArg[i].IndexOf(strParaName) >= 0)
                {
                    result = System.Web.HttpUtility.UrlDecode(strUrlArg[i].Split('=')[1], System.Text.Encoding.GetEncoding("gb2312"));
                    break;
                }
            }
            return result;
        }

        #endregion Private
    }
}
